package com.abel.bigwater.wflow

import org.activiti.api.runtime.shared.query.Pageable
import org.activiti.api.task.runtime.TaskRuntime
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.set
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod

@RequestMapping("/")
@Controller
class HelloController {

    @Autowired
    var userDetailService: UserDetailsService? = null

    @Autowired
    var taskRuntime: TaskRuntime? = null

    @RequestMapping("/hello")
    fun hello(m: Model): String {
        val ctx = SecurityContextHolder.getContext()
        val auth = ctx.authentication

        if (auth.principal is UserDetails) {
            m.set("user", auth.principal as User)

            val tlist = taskRuntime?.tasks(Pageable.of(0, 20))?.content.orEmpty()
            m.set("taskList", tlist)

            return "hello"
        } else {
            return "login"
        }
    }

    @RequestMapping("/userList")
    fun userList(m: Model): String {
        m.set("userList", listOf(User("system", "demo", emptyList()),
                User("admin", "demo", emptyList())))

        return "user-list"
    }

    @RequestMapping(value = ["/login"], method = [RequestMethod.GET])
    fun login(): String {
        return "login"
    }

    @RequestMapping("/index")
    fun root(m: Model): String {
        val ctx = SecurityContextHolder.getContext()
        val auth = ctx.authentication

        if (auth.principal is UserDetails) {
            m.set("user", auth.principal as User)

            val tlist = taskRuntime?.tasks(Pageable.of(0, 20))?.content.orEmpty()
            m.set("taskList", tlist)

            return "hello"
        } else {
            return "login"
        }
    }
}